package com.jzo2o.customer.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jzo2o.common.model.PageResult;
import com.jzo2o.common.utils.BeanUtils;
import com.jzo2o.common.utils.UserContext;
import com.jzo2o.customer.enums.AuditStatusEnum;
import com.jzo2o.customer.enums.CertificationStatusEnum;
import com.jzo2o.customer.mapper.WorkerAuditMapper;
import com.jzo2o.customer.mapper.WorkerCertificationMapper;
import com.jzo2o.customer.model.domain.WorkerAudit;
import com.jzo2o.customer.model.domain.WorkerCertification;
import com.jzo2o.customer.model.dto.WorkerCertificationUpdateDTO;
import com.jzo2o.customer.model.dto.request.CertificationAuditReqDTO;
import com.jzo2o.customer.model.dto.request.WorkerCertificationAuditAddReqDTO;
import com.jzo2o.customer.model.dto.request.WorkerCertificationAuditPageQueryReqDTO;
import com.jzo2o.customer.model.dto.response.RejectReasonResDTO;
import com.jzo2o.customer.model.dto.response.WorkerCertificationAuditResDTO;
import com.jzo2o.customer.model.dto.response.WorkerCertificationResDTO;
import com.jzo2o.customer.service.IWorkerCertificationService;
import com.jzo2o.mysql.utils.PageHelperUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;

/**
 * <p>
 * 服务人员认证信息表 服务实现类
 * </p>
 *
 * @author itcast
 * @since 2023-09-06
 */
@Service
public class WorkerCertificationServiceImpl extends ServiceImpl<WorkerCertificationMapper, WorkerCertification> implements IWorkerCertificationService {
    @Resource
    private WorkerCertificationMapper workerCertificationMapper;
    @Resource
    private WorkerAuditMapper workerAuditMapper;


    /**
     * 根据服务人员id更新
     *
     * @param workerCertificationUpdateDTO 服务人员认证更新模型
     */
    @Override
    public void updateById(WorkerCertificationUpdateDTO workerCertificationUpdateDTO) {
        LambdaUpdateWrapper<WorkerCertification> updateWrapper = Wrappers.<WorkerCertification>lambdaUpdate()
                .eq(WorkerCertification::getId, workerCertificationUpdateDTO.getId())
                .set(WorkerCertification::getCertificationStatus, workerCertificationUpdateDTO.getCertificationStatus())
                .set(ObjectUtil.isNotEmpty(workerCertificationUpdateDTO.getName()), WorkerCertification::getName, workerCertificationUpdateDTO.getName())
                .set(ObjectUtil.isNotEmpty(workerCertificationUpdateDTO.getIdCardNo()), WorkerCertification::getIdCardNo, workerCertificationUpdateDTO.getIdCardNo())
                .set(ObjectUtil.isNotEmpty(workerCertificationUpdateDTO.getFrontImg()), WorkerCertification::getFrontImg, workerCertificationUpdateDTO.getFrontImg())
                .set(ObjectUtil.isNotEmpty(workerCertificationUpdateDTO.getBackImg()), WorkerCertification::getBackImg, workerCertificationUpdateDTO.getBackImg())
                .set(ObjectUtil.isNotEmpty(workerCertificationUpdateDTO.getCertificationMaterial()), WorkerCertification::getCertificationMaterial, workerCertificationUpdateDTO.getCertificationMaterial())
                .set(ObjectUtil.isNotEmpty(workerCertificationUpdateDTO.getCertificationTime()), WorkerCertification::getCertificationTime, workerCertificationUpdateDTO.getCertificationTime());
        super.update(updateWrapper);
    }

    /**
     * 服务端提交认证申请
     *
     * @param auditAddReqDTO 认证申请模型
     */
    @Override
    @Transactional
    public WorkerCertification  submitAuth(WorkerCertificationAuditAddReqDTO auditAddReqDTO) {
        //1、获取服务人员id
        Long workerId  = UserContext.currentUserId();

        //2、dto转换为实体
        WorkerCertification workerCertification = BeanUtils.toBean(auditAddReqDTO, WorkerCertification.class);

        //3、将状态改为认证中、设置id、创建和更新时间
        workerCertification.setCertificationStatus(CertificationStatusEnum.PROGRESSING.getStatus());
        workerCertification.setId(workerId);
        workerCertification.setCreateTime(LocalDateTime.now());
        workerCertification.setUpdateTime(LocalDateTime.now());

        //4、保存
        this.saveOrUpdate(workerCertification);

        //5、修改worker_audit表信息
        WorkerAudit workerAudit = new WorkerAudit();
        workerAudit.setId(workerId);
        workerAudit.setAuditStatus(AuditStatusEnum.UNAUDITED.getStatus());
        workerAudit.setUpdateTime(LocalDateTime.now());
        workerAuditMapper.insert(workerAudit);

        return workerCertification;
    }

    /**
     * 获取驳回原因
     *
     * @param certificationAuditReqDTO 认证审核参数
     * @return 驳回原因
     */
    @Override
    public RejectReasonResDTO rejectReason(CertificationAuditReqDTO certificationAuditReqDTO) {
        //创建响应对象
        RejectReasonResDTO rejectReasonResDTO = new RejectReasonResDTO();
        //设置驳回原因
        rejectReasonResDTO.setRejectReason(certificationAuditReqDTO.getRejectReason());

        //返回结果
        return rejectReasonResDTO;
    }

    /**
     * 审核服务人员认证分页查询
     *
     * @param workerCertificationPageQueryReqDTO
     * @return
     */
    @Override
    public PageResult<WorkerCertificationAuditResDTO> page(WorkerCertificationAuditPageQueryReqDTO workerCertificationPageQueryReqDTO) {
        PageResult<WorkerCertificationAuditResDTO> pageResult = PageHelperUtils.selectPage(
                workerCertificationPageQueryReqDTO,
                () -> workerCertificationMapper.queryWorkerCertification()
        );
        return pageResult;
    }

    /**
     * 审核服务人员认证信息
     *
     * @param id
     * @param certificationStatus
     * @param rejectReason
     */
    @Override
    @Transactional
    public void audit(Long id, Integer certificationStatus, String rejectReason) {
        //1.更新worker_certification表
        LambdaUpdateWrapper<WorkerCertification> updateWrapper = new LambdaUpdateWrapper<WorkerCertification>()
                .set(WorkerCertification::getCertificationStatus, certificationStatus)
                .set(WorkerCertification::getUpdateTime, LocalDateTime.now())
                .eq(WorkerCertification::getId, id);
        //1.2、如果认证状态为：认证成功，则更新认证时间
        if (certificationStatus == CertificationStatusEnum.SUCCESS.getStatus()) {
            updateWrapper.set(WorkerCertification::getCertificationTime, LocalDateTime.now());
        }
        //1.3、更新
        this.update(updateWrapper);

        //2.更新worker_audit表
        //2.1、检查是否已存在该服务人员的审核记录
        WorkerAudit workerAudit = workerAuditMapper.selectById(id);
//       //2.1.1、如果不存在，则创建一条新的审核记录
        if (workerAudit == null) {
            workerAudit = new WorkerAudit();
            workerAudit.setId(id);
            workerAuditMapper.insert(workerAudit);
        }
        //2.1.2、如果存在，则更新现有记录
        workerAudit.setAuditStatus(AuditStatusEnum.AUDITED.getStatus());
        workerAudit.setAuditTime(LocalDateTime.now());
        workerAudit.setRejectReason(rejectReason);
        workerAudit.setUpdateTime(LocalDateTime.now());
        workerAudit.setAuditorId(UserContext.currentUserId());
        workerAudit.setAuditorName(UserContext.currentUser().getName());

        //3、更新
        workerAuditMapper.updateById(workerAudit);
    }
}
